package com.userservice.controller;

import annotation.DisableBaseResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.userservice.generator.service.LoginService;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import generator.domain.Login;
import generator.support.ResponseResult;
import generator.vo.ResetPwd;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.MD5Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/user")
@CrossOrigin
@Slf4j
@RestController
public class UserController {

    @Autowired
    LoginService loginService;

    /**
     * 分布式测试接口（待删）
     */
    @GetMapping("/get")
    public List<Login> getDept(){
        log.info("UserController -> getDept");
        return loginService.list();
    }

    /**
     * 生成验证码图片接口
     * @param request http请求
     * @param response http响应
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response){
        log.info("UserController -> getCaptcha");
        SpecCaptcha captcha = new SpecCaptcha(130, 48);
        try {
            CaptchaUtil.out(captcha, request, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录功能
     * @param username 账号
     * @param password 密码
     * @param captcha 验证码
     * @param request 获取session中的验证码
     * @return 是否登陆成功
     */
    @GetMapping("/login")
    @DisableBaseResponse
    public ResponseResult<Login> login(@RequestParam String username,
                                       @RequestParam String password,
                                       @RequestParam String captcha,
                                       HttpServletRequest request){
        // 测试用例
        if ("000".equals(username) && "111".equals(password)){
            return new ResponseResult<>();
        }
        // 首先判断用户名密码是否正确
        QueryWrapper<Login> qw = new QueryWrapper<>();
        qw.eq("user_account", username);
        List<Login> list = loginService.list(qw);
        if (list.isEmpty()){
            // 用户不存在
            return new ResponseResult<>(400, "用户名或密码错误");
        } else {
            // 用户存在
            Login login = list.get(0);
            if (login.getUserStatus() == 1){
                return new ResponseResult<>(400, "账户已锁定，请联系管理员解锁");
            }
            String s = MD5Util.md5To32String(password, login.getUserSalt(), login.getUserIndex());
            if (s.equals(login.getUserPwd())){
                // 账号密码正确，判断验证码
                if (!CaptchaUtil.ver(captcha, request)){
                    CaptchaUtil.clear(request);
                    return new ResponseResult<>(400, "验证码错误");
                }
                login.setUserError(0);
                loginService.updateById(login);
                return new ResponseResult<>(login);
            } else {
                // 增加登录失败次数
                login.setUserError(login.getUserError() + 1);
                if (login.getUserError() == 5){
                    login.setUserStatus(1);
                    loginService.updateById(login);
                    return new ResponseResult<>(400, "错误次数过多，账号已锁定");
                }
                loginService.updateById(login);
                return new ResponseResult<>(400, "用户名或密码错误");
            }
        }
    }

    /**
     * 根据ID获取用户信息，密码除外
     */
    @GetMapping("/getInfo/{id}")
    public Login getInfo(@PathVariable String id){
        int temp = -1;
        try{
            temp = Integer.parseInt(id);
        } catch (NumberFormatException e){
            return null;
        }
        QueryWrapper<Login> loginQw = new QueryWrapper<>();
        loginQw.eq("user_id", temp);
        List<Login> list = loginService.list(loginQw);
        Login login = list.get(0);
        login.setUserPwd("");
        return login;
    }

    /**
     * 修改密码
     */
    @PostMapping("/reset")
    @DisableBaseResponse
    public ResponseResult<Object> reserPwd(@RequestBody ResetPwd reset){
        System.out.println(reset);
        int temp = -1;
        try{
            temp = Integer.parseInt(reset.getLoginId());
        } catch (NumberFormatException e){
            return new ResponseResult<>(400, "非法请求");
        }
        // 查看该用户是否存在
        QueryWrapper<Login> loginQw = new QueryWrapper<>();
        loginQw.eq("user_id", reset.getLoginId());
        List<Login> logins = loginService.list(loginQw);
        if (logins.isEmpty()){
            return new ResponseResult<>(400, "不存在该用户");
        }

        // 查看原密码是否相同
        Login lo = logins.get(0);
        if (!lo.getUserPwd().equals(MD5Util.md5To32String(reset.getOldPwd(), lo.getUserSalt(), lo.getUserIndex()))){
            return new ResponseResult<>(400, "原密码有误，请重新输入");
        }

        // 密码加密
        String salt = RandomStringUtils.randomAlphabetic(10);
        int index = (int)(Math.random() * 10);
        String s = MD5Util.md5To32String(reset.getNewPwd(), salt, index);

        UpdateWrapper<Login> updateQw = new UpdateWrapper<>();
        updateQw.eq("user_id", temp);
        updateQw.set("user_salt", salt);
        updateQw.set("user_index", index);
        updateQw.set("user_pwd", s);
        if (loginService.update(updateQw)){
            return new ResponseResult<>();
        }

        return new ResponseResult<>(400, "修改失败");
    }


}
